package main

import (
	"bytes"
	"fmt"
	"image"
	"image/jpeg"
	_ "image/jpeg"
	_ "image/png"
	"io/fs"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/nfnt/resize"
)

func resizeImage(originalImage *bytes.Buffer, width uint, ext string) (*bytes.Buffer, error) {
	image, _, err := image.Decode(originalImage)

	if err != nil {
		return nil, err
	}

	//newImage := resize.Thumbnail(width, width, image, resize.NearestNeighbor)
	newImage := resize.Resize(width, 0, image, resize.NearestNeighbor)

	out := new(bytes.Buffer)
	/*
		switch ext {
		case ".png":
			png.Encode(out, newImage)
		case ".jpg", ".jpeg":
		}*/
	jpeg.Encode(out, newImage, nil)

	return out, nil
}

func main() {
	//out := os.Stdout
	if !(len(os.Args) == 3) {
		panic("usage go run main.go . [width]")
	}
	path := os.Args[1]

	width, err := strconv.ParseUint(os.Args[2], 10, 0)

	if err != nil {
		panic("Wrong value for image width")
	}

	files, err := os.ReadDir(path)

	if err != nil {
		panic("Wrong value for image width")
	}

	err = os.MkdirAll("output"+string(os.PathSeparator)+strconv.FormatUint(width, 10), 0777)
	if err != nil {
		panic(err)
	}

	for _, file := range files {
		if !file.IsDir() {
			if err != nil {
				panic(err)
			}
			fmt.Print(file.Name(), " => ")
			switch filepath.Ext(file.Name()) {
			case ".png", ".jpg", ".jpeg":
				originalImage, err := ioutil.ReadFile(path + string(os.PathSeparator) + file.Name())
				if err != nil {
					panic(err)
				}
				newImage, err := resizeImage(bytes.NewBuffer(originalImage), uint(width), filepath.Ext(file.Name()))

				filename := file.Name()
				filename = strings.Replace(filename, ".png", ".jpg", 1)
				filename = strings.Replace(filename, ".jpeg", ".jpg", 1)
				filename = "output" + string(os.PathSeparator) + strconv.FormatUint(width, 10) + string(os.PathSeparator) + filename
				fmt.Println(filename)
				err = os.WriteFile(filename, newImage.Bytes(), fs.ModePerm)

				if err != nil {
					panic(err)
				}
			}
		}
	}
}
